﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GabageFactory.Models;
using GabageFactory.Utiliy.Crypt;

namespace GabageFactory.Controllers
{
    [Authorize]
    public class RecordController : BaseController
    {
        StackReposity stackReposity = new StackReposity();

        StackWaterReposity stackWaterReposity = new StackWaterReposity();

        PoolReposity poolReposity = new PoolReposity();

        StackBackWaterReposity stackBackWaterReposity = new StackBackWaterReposity();

        DikeSettleOffsetReposity dikeSettleOffsetReposity = new DikeSettleOffsetReposity();

        StackArdealiteReposity stackArdealiteReposity = new StackArdealiteReposity();

        TailingpondBackWaterReposity tailingpondBackWaterReposity = new TailingpondBackWaterReposity();

        TailingpondDailyWaterReposity tailingpondDailyWaterReposity = new TailingpondDailyWaterReposity();

        TailingpondDitchReposity tailingpondDitchReposity = new TailingpondDitchReposity();

        TailingpondFilldamReposity tailingpondFilldamReposity = new TailingpondFilldamReposity();

        FactoryWeatherReposity factoryWeatherReposity = new FactoryWeatherReposity();
        //
        // GET: /Record/StackWater/5
        public ActionResult StackWater(int id, int? factoryId, DateTime? date)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            ViewData["id"] = id;
            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator && date.HasValue && factoryId.HasValue)
            {
                now = date.Value;
                fId = factoryId.Value;
            }
            ViewData["factoryId"] = fId;
            
            IEnumerable<Return_Water_Pond_Base_Info> pools = poolReposity.ListPools(id);
            int poolNum = pools.Count();
            if (poolNum <= 0)
            {
                poolNum = 1;
            }

            stack_pool_daily_water_info[] poolWaterInfoArray = new stack_pool_daily_water_info[poolNum];
            IEnumerable<stack_pool_daily_water_info> poolWaterInfos = stackWaterReposity.GetDailyPoolWaterInfo(id, now);

            for (int i = 0; i < poolNum; i++)
            {
                if (poolWaterInfos != null && i < poolWaterInfos.Count())
                {
                    poolWaterInfoArray[i] = poolWaterInfos.ElementAt(i);
                }
                else
                {
                    stack_pool_daily_water_info poolDailyWaterInfo = new stack_pool_daily_water_info();
                    poolDailyWaterInfo.stack_id = id;
                    poolDailyWaterInfo.pool_no = i;
                    poolDailyWaterInfo.date = now.Date;
                    poolWaterInfoArray[i] = poolDailyWaterInfo;
                }
            }
            ViewData["poolWaterInfos"] = poolWaterInfoArray;

            stack_daily_water_info waterInfo = stackWaterReposity.GetDailyWaterInfo(id, now);
            if (waterInfo == null)
            {
                waterInfo = new stack_daily_water_info();
                waterInfo.stack_id = id;
                waterInfo.date = now.Date;
            }

            stack_monthly_phosphorus_fluorin phosphorus_fluorin = stackWaterReposity.GetWeeklyPhosphorusFluorin(id, now);
            if (phosphorus_fluorin != null)
            {
                waterInfo.total_down_ammonia = phosphorus_fluorin.total_down_ammonia;
                waterInfo.total_down_fluorin = phosphorus_fluorin.total_down_fluorin;
                waterInfo.total_down_nitrogen = phosphorus_fluorin.total_down_nitrogen;
                waterInfo.total_down_phosphorus = phosphorus_fluorin.total_down_phosphorus;
                waterInfo.total_up_ammonia = phosphorus_fluorin.total_up_ammonia;
                waterInfo.total_up_fluorin = phosphorus_fluorin.total_up_fluorin;
                waterInfo.total_up_nitrogen = phosphorus_fluorin.total_up_nitrogen;
                waterInfo.total_up_phosphorus = phosphorus_fluorin.total_up_phosphorus;
            }

            ShowUserList(fId, RoleEnum.Observer, waterInfo.tester_id);
            ViewData["success"] = false;
            return View(waterInfo);
        }

        [HttpPost]
        public ActionResult StackWater(stack_daily_water_info dailyWaterInfo, FormCollection collection)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator)
            {
                now = dailyWaterInfo.date;
                fId = long.Parse(collection.Get("factoryId"));
            }
            ViewData["factoryId"] = fId;
            int id = dailyWaterInfo.stack_id;
            ViewData["id"] = id;

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            dailyWaterInfo.date = now.Date;
            stack_daily_water_info oldDailyWaterInfo = stackWaterReposity.GetDailyWaterInfo(id, now);
            if (oldDailyWaterInfo != null)
            {
                stackWaterReposity.DeleteWaterInfo(oldDailyWaterInfo);
            }
            stackWaterReposity.CreateWaterInfo(dailyWaterInfo);

            
            stackWaterReposity.DeleteDailyPoolWaterInfos(id, now);
            int poolNum = parseInt(collection.Get("poolNum"));
            for (int i = 1; i <= poolNum; i++)
            {
                float poolWaterLevel = parseFloat(collection.Get("pool_water_level" + i));
                float poolWaterPH = parseFloat(collection.Get("pool_water_ph" + i));
                float poolWaterCapacity = parseFloat(collection.Get("pool_water_capacity" + i));
                stack_pool_daily_water_info poolDailyWaterInfo = new stack_pool_daily_water_info();
                poolDailyWaterInfo.stack_id = id;
                poolDailyWaterInfo.date = now.Date;
                poolDailyWaterInfo.pool_no = i;
                if (!string.IsNullOrEmpty(collection.Get("pool_water_level" + i))) poolDailyWaterInfo.pool_water_level = poolWaterLevel;
                if (!string.IsNullOrEmpty(collection.Get("pool_water_ph" + i))) poolDailyWaterInfo.pool_water_ph = poolWaterPH;
                if (!string.IsNullOrEmpty(collection.Get("pool_water_capacity" + i))) poolDailyWaterInfo.pool_water_capacity = poolWaterCapacity;
                stackWaterReposity.CreateDailyPoolWaterInfo(poolDailyWaterInfo);
            }

            stack_pool_daily_water_info[] poolWaterInfoArray = new stack_pool_daily_water_info[poolNum];
            IEnumerable<stack_pool_daily_water_info> poolWaterInfos = stackWaterReposity.GetDailyPoolWaterInfo(id, now);

            IEnumerable<Return_Water_Pond_Base_Info> pools = poolReposity.ListPools(id);
            poolNum = pools.Count();
            if (poolNum <= 0)
            {
                poolNum = 1;
            }
            for (int i = 0; i < poolNum; i++)
            {
                if (poolWaterInfos != null && i < poolWaterInfos.Count())
                {
                    poolWaterInfoArray[i] = poolWaterInfos.ElementAt(i);
                }
                else
                {
                    stack_pool_daily_water_info poolDailyWaterInfo = new stack_pool_daily_water_info();
                    poolDailyWaterInfo.stack_id = id;
                    poolDailyWaterInfo.pool_no = i;
                    poolDailyWaterInfo.date = now.Date;
                    poolWaterInfoArray[i] = poolDailyWaterInfo;
                }
            }
            ViewData["poolWaterInfos"] = poolWaterInfoArray;

            stack_monthly_phosphorus_fluorin old_phosphorus_fluorin = stackWaterReposity.GetWeeklyPhosphorusFluorin(id, now);
            if (old_phosphorus_fluorin != null)
            {
                stackWaterReposity.DeleteWeeklyPhosphorusFluorin(old_phosphorus_fluorin);
            }
            stack_monthly_phosphorus_fluorin phosphorus_fluorin = new stack_monthly_phosphorus_fluorin();
            phosphorus_fluorin.stack_id = dailyWaterInfo.stack_id;
            phosphorus_fluorin.date = Tools.GetWeeklyDate(dailyWaterInfo.date);
            phosphorus_fluorin.total_down_ammonia = dailyWaterInfo.total_down_ammonia;
            phosphorus_fluorin.total_down_fluorin = dailyWaterInfo.total_down_fluorin;
            phosphorus_fluorin.total_down_nitrogen = dailyWaterInfo.total_down_nitrogen;
            phosphorus_fluorin.total_down_phosphorus = dailyWaterInfo.total_down_phosphorus;
            phosphorus_fluorin.total_up_ammonia = dailyWaterInfo.total_up_ammonia;
            phosphorus_fluorin.total_up_fluorin = dailyWaterInfo.total_up_fluorin;
            phosphorus_fluorin.total_up_nitrogen = dailyWaterInfo.total_up_nitrogen;
            phosphorus_fluorin.total_up_phosphorus = dailyWaterInfo.total_up_phosphorus;
            stackWaterReposity.CreateMonthlyPhosphorusFluorin(phosphorus_fluorin);

            ShowUserList(fId, RoleEnum.Observer, dailyWaterInfo.tester_id);
            ViewData["success"] = true;
            return View(dailyWaterInfo);
        }

        //
        // GET: /Record/BackWater/5
        public ActionResult BackWater(int id, long? factoryId, DateTime? date)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            Stack stack = stackReposity.GetStackById(id);

            if (stack != null)
            {
                ViewData["flowInPic"] = stack.FlowInPic;
            }

            ViewData["id"] = id;
            DateTime now = DateTime.Now;

            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator && date.HasValue && factoryId.HasValue)
            {
                now = date.Value;
                fId = factoryId.Value;
            }
            ViewData["factoryId"] = fId;

            stack_backwater_info backWaterInfo = stackBackWaterReposity.GetDailyBackWaterInfo(id, now);
            if (backWaterInfo == null)
            {
                backWaterInfo = new stack_backwater_info();
                backWaterInfo.stack_id = id;
                backWaterInfo.date = now.Date;
                backWaterInfo.siphon_caliber = 500;
            }
            ShowUserList(fId, RoleEnum.Observer, backWaterInfo.tester_id);
            ViewData["success"] = false;
            return View(backWaterInfo);
        }

        [HttpPost]
        public ActionResult BackWater(stack_backwater_info backWaterInfo, FormCollection collection)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            int id = backWaterInfo.stack_id;
            ViewData["id"] = id;

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator)
            {
                now = backWaterInfo.date;
                fId = long.Parse(collection.Get("factoryId"));
            }
            ViewData["factoryId"] = fId;
            backWaterInfo.date = now.Date;

            stack_backwater_info oldBackWaterInfo = stackBackWaterReposity.GetDailyBackWaterInfo(id, now);
            if (oldBackWaterInfo != null)
            {
                stackBackWaterReposity.DeleteWaterInfo(oldBackWaterInfo);
            }
            stackBackWaterReposity.CreateBackWaterInfo(backWaterInfo);
            ViewData["success"] = true;

            Stack stack = stackReposity.GetStackById(id);

            if (stack != null)
            {
                ViewData["flowInPic"] = stack.FlowInPic;
            }

            ShowUserList(fId, RoleEnum.Observer, backWaterInfo.tester_id);
            return View(backWaterInfo);
        }

        //
        // GET: /Record/Settle/5
        public ActionResult Settle(int id, int? factoryId, DateTime? date)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            ViewData["id"] = id;
            DateTime now = DateTime.Now;

            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator && date.HasValue && factoryId.HasValue)
            {
                now = date.Value;
                fId = factoryId.Value;
            }
            ViewData["factoryId"] = fId;
            ViewData["originalDate"] = now;

            DateTime monthDate = new DateTime(now.Year, now.Month, 1);

            stack_settle_offset settleOffset = dikeSettleOffsetReposity.GetDikeSettleInfo(id, now);
            if (settleOffset == null)
            {
                settleOffset = new stack_settle_offset();
                settleOffset.stack_id = id;
                settleOffset.date = monthDate;
            }

            IEnumerable<Return_Water_Pond_Base_Info> pools = poolReposity.ListPools(id);
            int poolNum = pools.Count();
            if (poolNum <= 0)
            {
                poolNum = 1;
            }

            stack_settle_offset_pool_info[] offsetPoolInfoArray = new stack_settle_offset_pool_info[poolNum];
            IEnumerable<stack_settle_offset_pool_info> offsetPoolInfos = dikeSettleOffsetReposity.GetMonthSettleOffsetPoolInfo(id, now);

            for (int i = 0; i < poolNum; i++)
            {
                if (offsetPoolInfos != null && i < offsetPoolInfos.Count())
                {
                    offsetPoolInfoArray[i] = offsetPoolInfos.ElementAt(i);
                }
                else
                {
                    stack_settle_offset_pool_info offsetPoolInfo = new stack_settle_offset_pool_info();
                    offsetPoolInfo.stack_id = id;
                    offsetPoolInfo.pool_no = i;
                    offsetPoolInfo.date = monthDate.Date;
                    offsetPoolInfoArray[i] = offsetPoolInfo;
                }
            }
            ViewData["offsetPoolInfos"] = offsetPoolInfoArray;

            ShowUserList(fId, RoleEnum.Observer, settleOffset.tester_id);
            
            ViewData["success"] = false;
            return View(settleOffset);
        }

        [HttpPost]
        public ActionResult Settle(stack_settle_offset settleOffset, FormCollection collection)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            int id = settleOffset.stack_id;
            ViewData["id"] = id;

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            DateTime now = DateTime.Now;

            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator)
            {
                now = settleOffset.date;
                fId = long.Parse(collection.Get("factoryId"));
            }
            ViewData["factoryId"] = fId;
            ViewData["originalDate"] = now;
            DateTime monthDate = new DateTime(now.Year, now.Month, 1);

            settleOffset.date = monthDate;
            stack_settle_offset oldSettleOffset = dikeSettleOffsetReposity.GetDikeSettleInfo(id, now);
            if (oldSettleOffset != null)
            {
                dikeSettleOffsetReposity.DeleteDikeSettleInfo(oldSettleOffset);
            }
            dikeSettleOffsetReposity.CreateDikeSettleInfo(settleOffset);


            dikeSettleOffsetReposity.DeleteSettleOffsetPoolInfos(id, monthDate);
            int poolNum = parseInt(collection.Get("poolNum"));
            for (int i = 1; i <= poolNum; i++)
            {
                float ditchEl = parseFloat(collection.Get("ditch_El" + i));
                stack_settle_offset_pool_info poolInfo = new stack_settle_offset_pool_info();
                poolInfo.stack_id = id;
                poolInfo.date = monthDate;
                poolInfo.pool_no = i;
                if (!string.IsNullOrEmpty(collection.Get("ditch_El" + i))) poolInfo.ditch_El = ditchEl;
                dikeSettleOffsetReposity.CreateSettleOffsetPoolInfo(poolInfo);
            }

            stack_settle_offset_pool_info[] offsetPoolInfoArray = new stack_settle_offset_pool_info[poolNum];
            IEnumerable<stack_settle_offset_pool_info> offsetPoolInfos = dikeSettleOffsetReposity.GetMonthSettleOffsetPoolInfo(id, now);

            IEnumerable<Return_Water_Pond_Base_Info> pools = poolReposity.ListPools(id);
            poolNum = pools.Count();
            if (poolNum <= 0)
            {
                poolNum = 1;
            }
            for (int i = 0; i < poolNum; i++)
            {
                if (offsetPoolInfos != null && i < offsetPoolInfos.Count())
                {
                    offsetPoolInfoArray[i] = offsetPoolInfos.ElementAt(i);
                }
                else
                {
                    stack_settle_offset_pool_info offsetPoolInfo = new stack_settle_offset_pool_info();
                    offsetPoolInfo.stack_id = id;
                    offsetPoolInfo.pool_no = i;
                    offsetPoolInfo.date = monthDate.Date;
                    offsetPoolInfoArray[i] = offsetPoolInfo;
                }
            }
            ViewData["offsetPoolInfos"] = offsetPoolInfoArray;

            ShowUserList(fId, RoleEnum.Observer, settleOffset.tester_id);
            ViewData["success"] = true;
            return View(settleOffset);
        }


        //
        // GET: /Record/Ardealite/5
        public ActionResult Ardealite(int id, int? factoryId, DateTime? date)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            ViewData["id"] = id;
            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator && date.HasValue && factoryId.HasValue)
            {
                now = date.Value;
                fId = factoryId.Value;
            }
            ViewData["factoryId"] = fId;

            stack_ardealite_ditch dailyArdealiteDitchInfo = stackArdealiteReposity.GetDailyArdealiteDitchInfo(id, now);
            if (dailyArdealiteDitchInfo == null)
            {
                dailyArdealiteDitchInfo = new stack_ardealite_ditch();
                dailyArdealiteDitchInfo.stack_id = id;
                dailyArdealiteDitchInfo.date = now.Date;
                dailyArdealiteDitchInfo.dike_downstream_slope_rate = "1:2.5";
            }

            ViewData["success"] = false;

            ShowUserList(fId, RoleEnum.Observer, dailyArdealiteDitchInfo.tester_id);
            return View(dailyArdealiteDitchInfo);
        }

        [HttpPost]
        public ActionResult Ardealite(stack_ardealite_ditch dailyArdealiteDitchInfo, FormCollection collection)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            int id = dailyArdealiteDitchInfo.stack_id;
            ViewData["id"] = id;

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator)
            {
                now = dailyArdealiteDitchInfo.date;
                fId = long.Parse(collection.Get("factoryId"));
            }
            ViewData["factoryId"] = fId;
            dailyArdealiteDitchInfo.date = now.Date;

            stack_ardealite_ditch oldDailyArdealiteDitchInfo = stackArdealiteReposity.GetDailyArdealiteDitchInfo(id, now);
            if (oldDailyArdealiteDitchInfo != null)
            {
                stackArdealiteReposity.DeleteArdealiteDitchInfo(oldDailyArdealiteDitchInfo);
            }
            stackArdealiteReposity.CreateArdealiteDitchInfo(dailyArdealiteDitchInfo);
            ViewData["success"] = true;
            ShowUserList(fId, RoleEnum.Observer, dailyArdealiteDitchInfo.tester_id);
            
            return View(dailyArdealiteDitchInfo);
        }

        //
        // GET: /Record/Ditch/5
        public ActionResult Ditch(int id, int? factoryId, DateTime? date, bool success = false)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            ViewData["id"] = id;
            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator && date.HasValue && factoryId.HasValue)
            {
                now = date.Value;
                fId = factoryId.Value;
            }
            ViewData["factoryId"] = fId;
            
            IEnumerable<Runoff_Interception_Ditch_Base_Info> ditches = poolReposity.ListDitches(id);
            List<Runoff_Interception_Ditch_Base_Info> usedDitches = ditches.Where(item => item.El > 0 && item.unused != 1).ToList();
            ViewData["ditchs"] = usedDitches;
            int i = 1;
            string ditchDesignPic = "";
            Stack stack = stackReposity.GetStackById(id);
            if (stack != null)
            {
                ditchDesignPic = stack.DitchDesignPic;
            }
            ViewData["ditchDesignPic"] = ditchDesignPic;
            StackDailyDitchReposity stackDailyDitchReposity = new StackDailyDitchReposity();
            long testerId = 0;
            string ditchNos = "";
            long stackId = 0;
            foreach (Runoff_Interception_Ditch_Base_Info ditch in usedDitches)
            {
                stackId = ditch.stack_id;
                Runoff_Interception_Ditch_daily_info ditchRecord = stackDailyDitchReposity.GetDailyDitchInfo(id, ditch.ditch_no, now);
                if (ditchRecord == null)
                {
                    ditchRecord = new Runoff_Interception_Ditch_daily_info();
                    ditchRecord.stack_id = id;
                    ditchRecord.date = now.Date;
                    ditchRecord.ditch_no = ditch.ditch_no;
                }
                ditchNos += ditch.ditch_no + " ";
                testerId = ditchRecord.tester_id.HasValue ? ditchRecord.tester_id.Value : 0;
                ViewData["dailyDitch" + ditch.ditch_no] = ditchRecord;
            }
            ditchNos = ditchNos.TrimEnd();
            ViewData["stack_id"] = stackId;
            ViewData["ditchNos"] = ditchNos;
            ViewData["date"] = now.Date;
            ViewData["success"] = success;

            ShowUserList(fId, RoleEnum.Observer, testerId);
            return View();
        }

        [HttpPost]
        public ActionResult Ditch(FormCollection collection)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            int id = parseInt(collection.Get("stack_id"));
            ViewData["id"] = id;

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator)
            {
                now = DateTime.Parse(collection.Get("date"));
                fId = long.Parse(collection.Get("factoryId"));
            }
            ViewData["factoryId"] = fId;
            StackDailyDitchReposity stackDailyDitchReposity = new StackDailyDitchReposity();
            string ditchNos = collection.Get("ditchNos");
            int tester_id = parseInt(collection.Get("tester_id"));
            if (!string.IsNullOrEmpty(ditchNos))
            {
                string[] nos = ditchNos.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                if (nos != null && nos.Length > 0)
                {
                    foreach (string no in nos)
                    {
                        int is_Sidewall_Crack = parseInt(collection.Get("is_Sidewall_Crack" + no));
                        string Sidewall_Crack_description = collection.Get("Sidewall_Crack_description" + no);
                        int is_Clogging = parseInt(collection.Get("is_Clogging" + no));
                        string Clogging_description = collection.Get("Clogging_description" + no);
                        int is_Instability = parseInt(collection.Get("is_Instability" + no));
                        string Instability_description = collection.Get("Instability_description" + no);
                        int is_Innerwall_Crack = parseInt(collection.Get("is_Innerwall_Crack" + no));
                        string Innerwall_Crack_description = collection.Get("Innerwall_Crack_description" + no);

                        Runoff_Interception_Ditch_daily_info runoff_Interception_Ditch_daily_info = new Runoff_Interception_Ditch_daily_info();
                        runoff_Interception_Ditch_daily_info.stack_id = id;
                        runoff_Interception_Ditch_daily_info.date = now.Date;
                        runoff_Interception_Ditch_daily_info.ditch_no = parseInt(no);
                        runoff_Interception_Ditch_daily_info.tester_id = tester_id;
                        runoff_Interception_Ditch_daily_info.is_Sidewall_Crack = is_Sidewall_Crack;
                        runoff_Interception_Ditch_daily_info.Sidewall_Crack_description = Sidewall_Crack_description;
                        runoff_Interception_Ditch_daily_info.is_Clogging = is_Clogging;
                        runoff_Interception_Ditch_daily_info.Clogging_description = Clogging_description;
                        runoff_Interception_Ditch_daily_info.is_Instability = is_Instability;
                        runoff_Interception_Ditch_daily_info.Instability_description = Instability_description;
                        runoff_Interception_Ditch_daily_info.is_Innerwall_Crack = is_Innerwall_Crack;
                        runoff_Interception_Ditch_daily_info.Innerwall_Crack_description = Innerwall_Crack_description;

                        Runoff_Interception_Ditch_daily_info oldDailyDitchInfo = stackDailyDitchReposity.GetDailyDitchInfo(id, parseInt(no), now);
                        if (oldDailyDitchInfo != null)
                        {
                            stackDailyDitchReposity.DeleteDitchInfo(oldDailyDitchInfo);
                        }
                        stackDailyDitchReposity.CreateDailyDitchInfo(runoff_Interception_Ditch_daily_info);
                    }
                }
            }

            return RedirectToAction("Ditch", new {id=id, factoryId=fId, date=now.Date, success = true });
        }

        //
        // GET: /Record/Ditch/5
        public ActionResult PiezometerWell(int id, int? factoryId, DateTime? date, bool success = false)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            ViewData["id"] = id;
            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator && date.HasValue && factoryId.HasValue)
            {
                now = date.Value;
                fId = factoryId.Value;
            }
            ViewData["originalDate"] = now.Date;
            now = new DateTime(now.Year, now.Month, 1);
            ViewData["factoryId"] = fId;

            PiezometerReposity piezometerReposity = new PiezometerReposity();
            PiezometerRecordReposity piezometerRecordReposity = new PiezometerRecordReposity();
            IEnumerable<Piezometer_well_base_info> wells = piezometerReposity.ListWell(id);
            List<Piezometer_well_monthly_info> wellsRecord = piezometerRecordReposity.GetMonthlyPiezometerWellInfo(id, now) ;
            ViewData["wells"] = wells.ToList();
            ViewData["wellsRecord"] = wellsRecord;
            string piezometerWellPic = "";
            Stack stack = stackReposity.GetStackById(id);
            if (stack != null)
            {
                piezometerWellPic = stack.PiezometerWellPic;
            }
            ViewData["piezometerWellPic"] = piezometerWellPic;

            ViewData["date"] = now.Date;
            ViewData["success"] = success;
            int testerId = 0;
            if (wellsRecord != null && wellsRecord.Count > 0)
            {
                testerId = wellsRecord[0].tester_id.HasValue ? wellsRecord[0].tester_id.Value : 0;
            }
            ShowUserList(fId, RoleEnum.Observer, testerId);
            return View();
        }

        [HttpPost]
        public ActionResult PiezometerWell(FormCollection collection)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            int id = parseInt(collection.Get("stack_id"));
            ViewData["id"] = id;

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator)
            {
                now = DateTime.Parse(collection.Get("date"));
                fId = long.Parse(collection.Get("factoryId"));
            }
            DateTime monthDate = new DateTime(now.Year, now.Month, 1);
            ViewData["factoryId"] = fId;

            PiezometerReposity piezometerReposity = new PiezometerReposity();
            PiezometerRecordReposity piezometerRecordReposity = new PiezometerRecordReposity();
            IEnumerable<Piezometer_well_base_info> wells = piezometerReposity.ListWell(id);
            int tester_id = parseInt(collection.Get("tester_id"));
            if (wells != null && wells.Count() > 0)
            {
                int i = 0;
                piezometerRecordReposity.DeletePiezometerWellInfos(id, monthDate);
                foreach (Piezometer_well_base_info well in wells)
                {
                    i++;
                    float Height_difference = parseFloat(collection.Get("Height_difference" + i));
                    string Remarks = collection.Get("Remarks" + i);

                    Piezometer_well_monthly_info piezometer_well_monthly_info = new Piezometer_well_monthly_info();
                    piezometer_well_monthly_info.tester_id = tester_id;
                    piezometer_well_monthly_info.Stack_id = well.Stack_id;
                    piezometer_well_monthly_info.date = monthDate;
                    piezometer_well_monthly_info.piezometer_well_id = well.piezometer_well_id;
                    piezometer_well_monthly_info.well_top_El = well.well_top_El;
                    piezometer_well_monthly_info.well_bottom_El = well.Well_bottom_El;
                    if (!string.IsNullOrEmpty(collection.Get("Height_difference" + i))) piezometer_well_monthly_info.Height_difference = Height_difference;
                    if (!string.IsNullOrEmpty(collection.Get("Height_difference" + i))) piezometer_well_monthly_info.Water_El = well.well_top_El - Height_difference;
                    piezometer_well_monthly_info.Remarks = Remarks;

                    piezometerRecordReposity.CreatePiezometerWellRecord(piezometer_well_monthly_info);
                }
            }

            return RedirectToAction("PiezometerWell", new { id = id, factoryId = fId, date = now.Date, success = true });
        }

        //
        // GET: /Record/Ditch/5
        public ActionResult PiezometerBase(int id, int? factoryId, DateTime? date, bool success = false)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            ViewData["id"] = id;
            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator && date.HasValue && factoryId.HasValue)
            {
                now = date.Value;
                fId = factoryId.Value;
            }
            ViewData["originalDate"] = now.Date;
            now = new DateTime(now.Year, now.Month, 1);
            ViewData["factoryId"] = fId;

            PiezometerReposity piezometerReposity = new PiezometerReposity();
            PiezometerRecordReposity piezometerRecordReposity = new PiezometerRecordReposity();
            IEnumerable<Piezometer_base_info> equaps = piezometerReposity.ListEquaps(id);
            List<Piezometer_monthly_info> equapsRecord = piezometerRecordReposity.GetMonthlyPiezometerBaseInfo(id, now);
            List<Piezometer_base_info> topEquaps = null;
            List<Piezometer_base_info> bottomEquaps = null;
            if (equaps != null && equaps.Count() > 0)
            {
                topEquaps = equaps.Where(item => item.piezometer_id == 1).ToList();
                bottomEquaps = equaps.Where(item => item.piezometer_id == 2).ToList(); ;
            }
            ViewData["topEquaps"] = topEquaps.ToList();
            ViewData["bottomEquaps"] = bottomEquaps.ToList();
            List<Piezometer_monthly_info> topEquapsRecord = null;
            List<Piezometer_monthly_info> bottomEquapsRecord = null;
            if (equapsRecord != null && equapsRecord.Count > 0)
            {
                topEquapsRecord = equapsRecord.Where(item => item.piezometer_id == 1).ToList();
                bottomEquapsRecord = equapsRecord.Where(item => item.piezometer_id == 2).ToList(); ;
            }
            ViewData["topEquapsRecord"] = topEquapsRecord;
            ViewData["bottomEquapsRecord"] = bottomEquapsRecord;
            string piezometerEquapPic = "";
            Stack stack = stackReposity.GetStackById(id);
            if (stack != null)
            {
                piezometerEquapPic = stack.PiezometerEquapPic;
            }
            ViewData["piezometerEquapPic"] = piezometerEquapPic;

            ViewData["date"] = now.Date;
            ViewData["success"] = success;
            int testerId = 0;
            if (equapsRecord != null && equapsRecord.Count > 0)
            {
                testerId = equapsRecord[0].tester_id.HasValue ? equapsRecord[0].tester_id.Value : 0;
            }
            ShowUserList(fId, RoleEnum.Observer, testerId);
            return View();
        }

        [HttpPost]
        public ActionResult PiezometerBase(FormCollection collection)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            int id = parseInt(collection.Get("stack_id"));
            ViewData["id"] = id;

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator)
            {
                now = DateTime.Parse(collection.Get("date"));
                fId = long.Parse(collection.Get("factoryId"));
            }
            DateTime monthDate = new DateTime(now.Year, now.Month, 1);
            ViewData["factoryId"] = fId;

            PiezometerReposity piezometerReposity = new PiezometerReposity();
            PiezometerRecordReposity piezometerRecordReposity = new PiezometerRecordReposity();
            IEnumerable<Piezometer_base_info> equaps = piezometerReposity.ListEquaps(id);
            List<Piezometer_base_info> topEquaps = equaps.Where(item => item.piezometer_id == 1).OrderBy(item => item.piezometer_hole_id).ToList();
            List<Piezometer_base_info> bottomEquaps = equaps.Where(item => item.piezometer_id == 2).OrderBy(item => item.piezometer_hole_id).ToList();
            int tester_id = parseInt(collection.Get("tester_id"));
            if (equaps != null && equaps.Count() > 0)
            {
                int i = 0;
                piezometerRecordReposity.DeletePiezometerBaseInfos(id, monthDate);
                foreach (Piezometer_base_info topEqual in topEquaps)
                {
                    Piezometer_base_info bottomEqual = bottomEquaps[i];
                    float gauge_Modulus_1 = parseFloat(collection.Get("gauge_Modulus_1_" + (i + 1)));
                    float gauge_temperature_1 = parseFloat(collection.Get("gauge_temperature_1_" + (i + 1)));
                    string Remarks_1 = collection.Get("Remarks_1_" + (i + 1));

                    Piezometer_monthly_info piezometer_monthly_info_top = new Piezometer_monthly_info();
                    piezometer_monthly_info_top.tester_id = tester_id;
                    piezometer_monthly_info_top.Stack_id = topEqual.Stack_id;
                    piezometer_monthly_info_top.date = monthDate;
                    piezometer_monthly_info_top.piezometer_hole_id = topEqual.piezometer_hole_id;
                    piezometer_monthly_info_top.piezometer_id = 1;
                    if (!string.IsNullOrEmpty(collection.Get("gauge_Modulus_1_" + (i + 1)))) piezometer_monthly_info_top.gauge_Modulus = gauge_Modulus_1;
                    if (!string.IsNullOrEmpty(collection.Get("gauge_temperature_1_" + (i + 1)))) piezometer_monthly_info_top.gauge_temperature = gauge_temperature_1;
                    piezometer_monthly_info_top.Remarks = Remarks_1;
                    if (!string.IsNullOrEmpty(collection.Get("gauge_Modulus_1_" + (i + 1))) && !string.IsNullOrEmpty(collection.Get("gauge_temperature_1_" + (i + 1))))
                    {
                        piezometer_monthly_info_top.gauge_Pressure_kpa = topEqual.Modulus_coefficient * (topEqual.Initial_Modulus - gauge_Modulus_1) - topEqual.Temperature_coefficient * (topEqual.Initial_temperature - gauge_temperature_1);
                        piezometer_monthly_info_top.gauge_Pressure_m = piezometer_monthly_info_top.gauge_Pressure_kpa / 9.81f;
                    }


                    float gauge_Modulus_2 = parseFloat(collection.Get("gauge_Modulus_2_" + (i + 1)));
                    float gauge_temperature_2 = parseFloat(collection.Get("gauge_temperature_2_" + (i + 1)));
                    string Remarks_2 = collection.Get("Remarks_2_" + (i + 1));


                    Piezometer_monthly_info piezometer_monthly_info_bottom = new Piezometer_monthly_info();
                    piezometer_monthly_info_bottom.tester_id = tester_id;
                    piezometer_monthly_info_bottom.Stack_id = topEqual.Stack_id;
                    piezometer_monthly_info_bottom.date = monthDate;
                    piezometer_monthly_info_bottom.piezometer_hole_id = topEqual.piezometer_hole_id;
                    piezometer_monthly_info_bottom.piezometer_id = 2;
                    if (!string.IsNullOrEmpty(collection.Get("gauge_Modulus_2_" + (i + 1)))) piezometer_monthly_info_bottom.gauge_Modulus = gauge_Modulus_2;
                    if (!string.IsNullOrEmpty(collection.Get("gauge_temperature_2_" + (i + 1)))) piezometer_monthly_info_bottom.gauge_temperature = gauge_temperature_2;
                    piezometer_monthly_info_bottom.Remarks = Remarks_2;
                    if (!string.IsNullOrEmpty(collection.Get("gauge_Modulus_2_" + (i + 1))) && !string.IsNullOrEmpty(collection.Get("gauge_temperature_2_" + (i + 1))))
                    {
                        piezometer_monthly_info_bottom.gauge_Pressure_kpa = bottomEqual.Modulus_coefficient * (bottomEqual.Initial_Modulus - gauge_Modulus_2) - bottomEqual.Temperature_coefficient * (bottomEqual.Initial_temperature - gauge_temperature_2);
                        piezometer_monthly_info_bottom.gauge_Pressure_m = piezometer_monthly_info_bottom.gauge_Pressure_kpa / 9.81f;
                        piezometer_monthly_info_bottom.Hydraulic_gradient = (topEqual.Installation_depth - bottomEqual.Installation_depth) / (piezometer_monthly_info_top.gauge_Pressure_m - piezometer_monthly_info_bottom.gauge_Pressure_m);
                        piezometer_monthly_info_top.Hydraulic_gradient = piezometer_monthly_info_bottom.Hydraulic_gradient;
                    }

                    piezometerRecordReposity.CreatePiezometerBaseRecord(piezometer_monthly_info_top);
                    piezometerRecordReposity.CreatePiezometerBaseRecord(piezometer_monthly_info_bottom);
                    i++;
                }
            }

            return RedirectToAction("PiezometerBase", new { id = id, factoryId = fId, date = now.Date, success = true });
        }

        //
        // GET: /Record/Ditch/5
        public ActionResult Drain(int id, int? factoryId, DateTime? date, bool success = false)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            ViewData["id"] = id;
            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator && date.HasValue && factoryId.HasValue)
            {
                now = date.Value;
                fId = factoryId.Value;
            }
            ViewData["originalDate"] = now.Date;
            now = new DateTime(now.Year, now.Month, 1);
            ViewData["factoryId"] = fId;

            DrainOutletReposity drainOutletReposity = new DrainOutletReposity();
            DrainRecordReposity drainRecordReposity = new DrainRecordReposity(); 
            IEnumerable<Drain_system_basic_info> drains = drainOutletReposity.ListDrains(id);
            Dictionary<Drain_system_basic_info, List<Drain_system_outlet_info>> drainOutlets = new Dictionary<Drain_system_basic_info, List<Drain_system_outlet_info>>();
            int i = 1;
            int testerId = 0;
            foreach (Drain_system_basic_info drain in drains)
            {
                IEnumerable<Drain_system_outlet_info> outlets = drainOutletReposity.ListDrainOutlets(drain.Stack_id, drain.El);
                List<Drain_system_outlet_info> outletList = new List<Drain_system_outlet_info>();
                foreach (Drain_system_outlet_info outlet in outlets)
                {
                    outletList.Add(outlet);
                }
                drainOutlets.Add(drain, outletList);
                List<Drain_system_Monthly_info> drainRecords = drainRecordReposity.GetMonthlyDrainInfo(id, drain.El, now);
                ViewData["drainRecords" + i] = drainRecords;
                if (drainRecords != null && drainRecords.Count > 0)
                {
                    testerId = drainRecords[0].tester_id.HasValue ? drainRecords[0].tester_id.Value : 0;
                }
                i++;
            }

            ViewData["drainOutlets"] = drainOutlets;

            ViewData["date"] = now.Date;
            ViewData["success"] = success;
            
            ShowUserList(fId, RoleEnum.Observer, testerId);
            return View();
        }

        [HttpPost]
        public ActionResult Drain(FormCollection collection)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            int id = parseInt(collection.Get("stack_id"));
            ViewData["id"] = id;

            if (!CanEditStack(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator)
            {
                now = DateTime.Parse(collection.Get("date"));
                fId = long.Parse(collection.Get("factoryId"));
            }
            DateTime monthDate = new DateTime(now.Year, now.Month, 1);
            ViewData["factoryId"] = fId;

            DrainOutletReposity drainOutletReposity = new DrainOutletReposity();
            DrainRecordReposity drainRecordReposity = new DrainRecordReposity();
            IEnumerable<Drain_system_basic_info> drains = drainOutletReposity.ListDrains(id);
            int tester_id = parseInt(collection.Get("tester_id"));
            if (drains != null && drains.Count() > 0)
            {
                int i = 1;
                drainRecordReposity.DeleteDrainInfos(id, monthDate);
                foreach (Drain_system_basic_info drain in drains)
                {
                    IEnumerable<Drain_system_outlet_info> outlets = drainOutletReposity.ListDrainOutlets(id, drain.El);
                    if (outlets != null && outlets.Count() > 0)
                    {
                        foreach(Drain_system_outlet_info outlet in outlets)
                        {
                            float Rate_Of_Flow = parseFloat(collection.Get("Rate_Of_Flow_" + i + "_" + outlet.Drain_outlet_no));
                            int Color_of_Flow = parseInt(collection.Get("Color_of_Flow_" + i + "_" + outlet.Drain_outlet_no));
                            int Deposit = parseInt(collection.Get("Deposit_" + i + "_" + outlet.Drain_outlet_no));
                            string Remarks = outlet.Is_In_Normal_Use.HasValue && outlet.Is_In_Normal_Use.Value != 1 ? "该出水口已不能正常监测" : "";

                            Drain_system_Monthly_info drainRecord = new Drain_system_Monthly_info();
                            drainRecord.tester_id = tester_id;
                            drainRecord.Stack_id = id;
                            drainRecord.Date = monthDate;
                            drainRecord.El = outlet.El;
                            drainRecord.Drain_outlet_no = outlet.Drain_outlet_no;
                            if (!string.IsNullOrEmpty(collection.Get("Rate_Of_Flow_" + i + "_" + outlet.Drain_outlet_no))) drainRecord.Rate_Of_Flow = Rate_Of_Flow;
                            drainRecord.Color_of_Flow = Color_of_Flow;
                            drainRecord.Deposit = Deposit;
                            drainRecord.Remarks = Remarks;

                            drainRecordReposity.CreateDrainRecord(drainRecord);
                        }
                    }
                    i++;
                }
            }

            return RedirectToAction("Drain", new { id = id, factoryId = fId, date = now.Date, success = true });
        }

        //
        // GET: /Record/TailingpondWater/5
        public ActionResult TailingpondWater(int id, int? factoryId, DateTime? date)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            if (!CanEditTailingpond(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            ViewData["id"] = id;
            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator && date.HasValue && factoryId.HasValue)
            {
                now = date.Value;
                fId = factoryId.Value;
            }
            ViewData["factoryId"] = fId;

            tailingpond_daily_water_info dailyWaterInfo = tailingpondDailyWaterReposity.GetDailyWaterInfo(id, now);
            if (dailyWaterInfo == null)
            {
                dailyWaterInfo = new tailingpond_daily_water_info();
                dailyWaterInfo.tailingpond_id = id;
                dailyWaterInfo.date = now.Date;
            }

            ShowUserList(fId, RoleEnum.Observer, dailyWaterInfo.tester_id);
            ViewData["success"] = false;
            return View(dailyWaterInfo);
        }

        [HttpPost]
        public ActionResult TailingpondWater(tailingpond_daily_water_info dailyWaterInfo, FormCollection collection)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            int id = dailyWaterInfo.tailingpond_id;
            ViewData["id"] = id;

            if (!CanEditTailingpond(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            DateTime now = DateTime.Now;

            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator)
            {
                now = dailyWaterInfo.date;
                fId = long.Parse(collection.Get("factoryId"));
            }
            ViewData["factoryId"] = fId;
            dailyWaterInfo.date = now.Date;

            tailingpond_daily_water_info oldDailyWaterInfo = tailingpondDailyWaterReposity.GetDailyWaterInfo(id, now);
            if (oldDailyWaterInfo != null)
            {
                tailingpondDailyWaterReposity.DeleteDailyWaterInfo(oldDailyWaterInfo);
            }
            tailingpondDailyWaterReposity.CreateDailyWaterInfo(dailyWaterInfo);
            ViewData["success"] = true;

            ShowUserList(fId, RoleEnum.Observer, dailyWaterInfo.tester_id);
            return View(dailyWaterInfo);
        }

        //
        // GET: /Record/TailingpondBackWater/5
        public ActionResult TailingpondBackWater(int id, int? factoryId, DateTime? date)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            if (!CanEditTailingpond(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            ViewData["id"] = id;
            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator && date.HasValue && factoryId.HasValue)
            {
                now = date.Value;
                fId = factoryId.Value;
            }
            ViewData["factoryId"] = fId;

            tailingpond_backwater_info backWaterInfo = tailingpondBackWaterReposity.GetDailyBackwaterInfo(id, now);
            if (backWaterInfo == null)
            {
                backWaterInfo = new tailingpond_backwater_info();
                backWaterInfo.tailingpond_id = id;
                backWaterInfo.date = now.Date;
            }

            ShowUserList(fId, RoleEnum.Observer, backWaterInfo.tester_id);
            ViewData["success"] = false;
            return View(backWaterInfo);
        }

        [HttpPost]
        public ActionResult TailingpondBackWater(tailingpond_backwater_info backWaterInfo, FormCollection collection)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            int id = backWaterInfo.tailingpond_id;
            ViewData["id"] = id;

            if (!CanEditTailingpond(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            DateTime now = DateTime.Now;

            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator)
            {
                now = backWaterInfo.date;
                fId = long.Parse(collection.Get("factoryId"));
            }
            ViewData["factoryId"] = fId;
            backWaterInfo.date = now.Date;

            tailingpond_backwater_info oldBackWaterInfo = tailingpondBackWaterReposity.GetDailyBackwaterInfo(id, now);
            if (oldBackWaterInfo != null)
            {
                tailingpondBackWaterReposity.DeleteBackWaterInfo(oldBackWaterInfo);
            }
            tailingpondBackWaterReposity.CreateBackWaterInfo(backWaterInfo);
            ShowUserList(fId, RoleEnum.Observer, backWaterInfo.tester_id);
            ViewData["success"] = true;
            return View(backWaterInfo);
        }

        //
        // GET: /Record/TailingpondDitch/5
        public ActionResult TailingpondDitch(int id, int? factoryId, DateTime? date)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            if (!CanEditTailingpond(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            ViewData["id"] = id;
            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator && date.HasValue && factoryId.HasValue)
            {
                now = date.Value;
                fId = factoryId.Value;
            }
            ViewData["factoryId"] = fId;

            tailingpond_daily_ditch_info ditchInfo = tailingpondDitchReposity.GetDailyDitchInfo(id, now);
            if (ditchInfo == null)
            {
                ditchInfo = new tailingpond_daily_ditch_info();
                ditchInfo.tailingpond_id = id;
                ditchInfo.date = now.Date;
            }
            ShowUserList(fId, RoleEnum.Observer, ditchInfo.tester_id);
            ViewData["success"] = false;
            return View(ditchInfo);
        }

        [HttpPost]
        public ActionResult TailingpondDitch(tailingpond_daily_ditch_info ditchInfo, FormCollection collection)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            int id = ditchInfo.tailingpond_id;
            ViewData["id"] = id;

            if (!CanEditTailingpond(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator)
            {
                now = ditchInfo.date;
                fId = long.Parse(collection.Get("factoryId"));
            }
            ViewData["factoryId"] = fId;

            ditchInfo.date = now.Date;

            tailingpond_daily_ditch_info oldDitchInfo = tailingpondDitchReposity.GetDailyDitchInfo(id, now);
            if (oldDitchInfo != null)
            {
                tailingpondDitchReposity.DeleteDailyDitch(oldDitchInfo);
            }
            tailingpondDitchReposity.CreateDailyDitch(ditchInfo);
            ViewData["success"] = true;
            ShowUserList(fId, RoleEnum.Observer, ditchInfo.tester_id);
            return View(ditchInfo);
        }

        //
        // GET: /Record/TailingpondFilldam/5
        public ActionResult TailingpondFilldam(int id, int? factoryId, DateTime? date)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            if (!CanEditTailingpond(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            ViewData["id"] = id;
            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator && date.HasValue && factoryId.HasValue)
            {
                now = date.Value;
                fId = factoryId.Value;
            }
            ViewData["factoryId"] = fId;

            tailingpond_daily_filldam_info filldamInfo = tailingpondFilldamReposity.GetDailyFilldamInfo(id, now);
            
            if (filldamInfo == null)
            {
                filldamInfo = new tailingpond_daily_filldam_info();
                filldamInfo.tailingpond_id = id;
                filldamInfo.date = now.Date;
            }
            ShowUserList(fId, RoleEnum.Observer, filldamInfo.tester_id);
            ViewData["success"] = false;
            return View(filldamInfo);
        }

        [HttpPost]
        public ActionResult TailingpondFilldam(tailingpond_daily_filldam_info filldamInfo, FormCollection collection)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            int id = filldamInfo.tailingpond_id;
            ViewData["id"] = id;

            if (!CanEditTailingpond(id))
            {
                return RedirectToAction("Deny", "Home");
            }

            DateTime now = DateTime.Now;
            long fId = GetCurrentUser().FactoryId;
            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator)
            {
                now = filldamInfo.date;
                fId = long.Parse(collection.Get("factoryId"));
            }
            ViewData["factoryId"] = fId;
            filldamInfo.date = now.Date;

            tailingpond_daily_filldam_info oldFilldamInfo = tailingpondFilldamReposity.GetDailyFilldamInfo(id, now);
            if (oldFilldamInfo != null)
            {
                tailingpondFilldamReposity.DeleteFilldamInfo(oldFilldamInfo);
            }
            tailingpondFilldamReposity.CreateFilldamInfo(filldamInfo);
            ViewData["success"] = true;
            ShowUserList(fId, RoleEnum.Observer, filldamInfo.tester_id);
            return View(filldamInfo);
        }


        //
        // GET: /Record/FactoryWeather/5
        public ActionResult FactoryWeather(int id)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            ViewData["id"] = id;
            DateTime now = DateTime.Now;

            Factory_daily_weather_info weatherInfo = factoryWeatherReposity.GetDailyWeatherInfo(id, now);
            if (weatherInfo == null)
            {
                weatherInfo = new Factory_daily_weather_info();
                weatherInfo.factory_id = id;
                weatherInfo.date = now.Date;
            }
            ShowUserList(GetCurrentUser().FactoryId, RoleEnum.Observer, weatherInfo.tester_id);
            
            ViewData["success"] = false;
            return View(weatherInfo);
        }

        [HttpPost]
        public ActionResult FactoryWeather(Factory_daily_weather_info weatherInfo)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            int id = weatherInfo.factory_id;
            ViewData["id"] = id;

            DateTime now = DateTime.Now;
            weatherInfo.date = now.Date;

            Factory_daily_weather_info oldWeatherInfo = factoryWeatherReposity.GetDailyWeatherInfo(id, now);
            if (oldWeatherInfo != null)
            {
                factoryWeatherReposity.DeleteDailyWeather(oldWeatherInfo);
            }
            factoryWeatherReposity.CreateDailyWeather(weatherInfo);
            ViewData["success"] = true;
            ShowUserList(GetCurrentUser().FactoryId, RoleEnum.Observer, weatherInfo.tester_id);
            
            return View(weatherInfo);
        }

        private bool CanEditStack(int id)
        {
            bool result = false;
            User currentUser = GetCurrentUser();

            if (currentUser.RoleId == (int)RoleEnum.Administrator)
            {
                result = true;
            }
            else if (currentUser.Factory.Stacks != null && currentUser.Factory.Stacks.Count > 0)
            {
                foreach (Stack stack in currentUser.Factory.Stacks)
                {
                    if (id == stack.Id)
                    {
                        result = true;
                        break;
                    }
                }
            }

            return result;
        }

        private bool CanEditTailingpond(int id)
        {
            bool result = false;
            User currentUser = GetCurrentUser();

            if (currentUser.RoleId == (int)RoleEnum.Administrator)
            {
                result = true;
            }
            else if (currentUser.Factory.Tailingponds != null && currentUser.Factory.Tailingponds.Count > 0)
            {
                foreach (Tailingpond tailingpond in currentUser.Factory.Tailingponds)
                {
                    if (id == tailingpond.Id)
                    {
                        result = true;
                        break;
                    }
                }
            }

            return result;
        }
    }
}
